<script setup lang="tsx">
import { activeListApi } from '@/api/Activity'
import { businessListApi } from '@/api/merchantManagement'
import type { ActiveListParams } from '@/api/Activity/types'
import Detail from './components/Detail.vue'
import { ElButton } from 'element-plus'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'
import { ActiveStateDict, VerifyTypeDict, dictToList } from '@/utils/dict'
import { hasPermission as hasPermis } from '@/components/Permission/src/utils'
// import { ActiveTypeDict, ActiveStateDict, dictToList } from '@/utils/dict'

const { t } = useI18n()

const activeTab = ref(0)

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await activeListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      activeType: 2,
      activeState: unref(activeTab) === 0 ? '' : unref(activeTab),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList } = tableMethods

const tabs = [
  {
    label: '全部',
    value: 0
  },
  {
    label: '进行中',
    value: 3
  },
  {
    label: '未开始',
    value: 2
  },
  {
    label: '已结束',
    value: 4
  }
]

const searchRef = ref()

const tabChange = (v) => {
  searchRef.value[0].reset()
  activeTab.value = v
  currentPage.value = 1
  searchParams.value = {}
  getList()
}

const getBusinessList = async () => {
  if (!hasPermis('GET /business/page')) {
    allSchemas.searchSchema.at(1)!.hidden = true
    return []
  }
  const res = await businessListApi({
    pageNum: 1,
    pageSize: 9999
  })
  return res.data.list?.map((v) => ({
    label: v.businessShortName,
    value: v.id
  }))
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: 'ID',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'activeNo',
    label: '活动编号',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 280,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <span>{row.activeNo}</span>
              {row.isPft && (
                <span
                  style={
                    'border: 1px solid #333;padding: 0 4px;margin-left: 6px;border-radius: 4px;'
                  }
                >
                  票付通
                </span>
              )}
            </>
          )
        }
      }
    }
  },
  {
    field: 'activeTitle',
    label: '活动名称',
    search: {
      componentProps: {
        placeholder: '请输入活动名称'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 220
    }
  },
  {
    field: 'activeStepPrices',
    label: '报名价格',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 220,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div v-html={getActiveStepPrices(row)}></div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'enrolledNum',
    label: '已报名人数',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'commissionAmt',
    label: '推广权益',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 220,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              {row.defaultCommissionType === 0 && (
                <div class={'flex items-center'}>
                  {row.otherEquity ? `其他：${row.otherEquity}` : '无'}
                </div>
              )}
              {row.defaultCommissionType === 1 && (
                <div class={'flex items-center'}>佣金：{row.commissionAmt}</div>
              )}
              {row.defaultCommissionType === 2 && (
                <div class={'flex items-center'}>佣金比例：{row.commissionRate}%</div>
              )}
            </>
          )
        }
      }
    }
  },
  {
    field: 'businessName',
    label: '活动商家',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'businessId',
    label: '活动商家',
    search: {
      component: 'Select',
      optionApi: async () => getBusinessList()
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'verifyType',
    label: '核销渠道',
    search: {
      component: 'Select',
      componentProps: {
        options: dictToList(VerifyTypeDict)
      }
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <span>{VerifyTypeDict[row.verifyType]}</span>
            </>
          )
        }
      }
    }
  },
  // {
  //   field: 'activeType',
  //   label: '活动类型',
  //   form: {
  //     hidden: true
  //   },
  //   search: {
  //     component: 'Select',
  //     componentProps: {
  //       options: dictToList(ActiveTypeDict)
  //     }
  //   },
  //   table: {
  //     slots: {
  //       default: (data: any) => {
  //         const row = data.row as any
  //         return (
  //           <>
  //             <span>{row.activeType && ActiveTypeDict[row.activeType]}</span>
  //           </>
  //         )
  //       }
  //     }
  //   }
  // },
  {
    field: 'activeState',
    label: '状态',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <span>{row.activeState && ActiveStateDict[row.activeState]}</span>
            </>
          )
        }
      }
    }
  },
  {
    field: 'time',
    label: '活动时间',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'startTime',
    label: '活动起止时间',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <span>{row.startTime}</span>至<span>{row.endTime}</span>
            </>
          )
        }
      }
    }
  },
  {
    field: 'validStartTime',
    label: '活动有效期',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <span>{row.validStartTime}</span>至<span>{row.validEndTime}</span>
            </>
          )
        }
      }
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 120,
      slots: {
        default: (data: any) => {
          const row = data.row as ActiveListParams
          return (
            <>
              <ElButton
                v-hasPermi="GET /active/details"
                type="primary"
                link
                onClick={() => details(row)}
              >
                查看详情
              </ElButton>
            </>
          )
        }
      }
    }
  }
])

const getActiveStepPrices = (row) => {
  let str = ''
  if (row.activeStepPrices.length > 0) {
    row.activeStepPrices.forEach((item) => {
      str += `<div>${item.enrollNum}人 ${item.enrollPrice.toFixed(2)}</div>`
    })
  } else {
    str = `<div>${row.enrollNum}人 ${row.activePrice.toFixed(2)}</div>`
  }
  return str
}

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  const { time, ...rest } = params
  let startTime, endTime
  if (time && time.length > 0) {
    startTime = time[0]
    endTime = time[1]
  }
  currentPage.value = 1
  searchParams.value = {
    startTime,
    endTime,
    ...rest
  }
  getList()
}

const showDrawer = ref(false)

const detailId = ref(0)

const details = async (row: any) => {
  console.log(row)
  detailId.value = row.id
  showDrawer.value = true
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3] ml-20px">
      <ElTabs v-model="activeTab" @tab-change="tabChange">
        <ElTabPane v-for="item in tabs" :key="item.value" :label="item.label" :name="item.value">
          <Search
            ref="searchRef"
            :schema="allSchemas.searchSchema"
            @reset="setSearchParams"
            @search="setSearchParams"
          />
          <Table
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :columns="allSchemas.tableColumns"
            :data="dataList"
            :loading="loading"
            @register="tableRegister"
            :pagination="{
              total
            }"
          />
        </ElTabPane>
      </ElTabs>
    </ContentWrap>

    <ElDrawer
      title="活动详情"
      v-model="showDrawer"
      direction="rtl"
      size="650px"
      @close="showDrawer = false"
    >
      <Detail v-if="showDrawer" :id="detailId" />
    </ElDrawer>
  </div>
</template>
